package chpt09.testsync;

public class SynchronizedCounterThreadTest {

	public static void main(String[] args) throws InterruptedException {
		int n = 1000; // 执行次数
		SyncCounter c = new SyncCounter();
		Thread t1 = new Thread(new SyncIncrementTask(n, c));
		Thread t2 = new Thread(new SyncIncrementTask(n, c));
		Thread t3 = new Thread(new SyncIncrementTask(n, c));
		Thread t4 = new Thread(new SyncDecrementTask(n, c));
		Thread t5 = new Thread(new SyncDecrementTask(n, c));
		Thread t6 = new Thread(new SyncDecrementTask(n, c));

		t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();
		t1.join();t2.join();t3.join();t4.join();t5.join();t6.join();
		System.out.println("sync counter's value = "+c.getValue());
		System.out.println("main end");
	}

}

class SyncCounter {
	private int value = 0;
	
	public void inc() {
		synchronized (this) {
			value++;
		}
	}
	public synchronized void dec() {
		value--;
	}
	public int getValue() {
		return value;
	}
}

class SyncIncrementTask implements Runnable{
	private int n;
	private SyncCounter c;

	public SyncIncrementTask(int n, SyncCounter c) {
		this.n = n;
		this.c = c;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++) {
			c.inc();
		}
	}
}

class SyncDecrementTask implements Runnable{
	private int n;
	private SyncCounter c;

	public SyncDecrementTask(int n, SyncCounter c) {
		this.n = n;
		this.c = c;
	}

	@Override
	public void run() {
		for (int i = 0; i < n; i++) {
			c.dec();
		}
	}
}